package com.atguigu.gmall.publisher.controller;

import com.atguigu.gmall.publisher.beans.KeywordStats;
import com.atguigu.gmall.publisher.beans.ProductStats;
import com.atguigu.gmall.publisher.beans.ProvinceStats;
import com.atguigu.gmall.publisher.beans.VisitorStats;
import com.atguigu.gmall.publisher.service.KeywordStatsService;
import com.atguigu.gmall.publisher.service.ProductStatsService;
import com.atguigu.gmall.publisher.service.ProvinceStatsService;
import com.atguigu.gmall.publisher.service.VisitorStatsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * 大屏展示的控制层
 *
 * @author lvbingbing
 * @date 2022-07-07 11:13
 */
@RestController
@RequestMapping("/api/sugar")
public class SugarController {

    @Autowired
    private ProductStatsService productStatsService;

    @Autowired
    private ProvinceStatsService provinceStatsService;

    @Autowired
    private VisitorStatsService visitorStatsService;

    @Autowired
    private KeywordStatsService keywordStatsService;

    @RequestMapping("/keyword")
    public String getKeywordStats(
            @RequestParam(value = "date", defaultValue = "0") Integer date,
            @RequestParam(value = "limit", defaultValue = "20") Integer limit) {
        if (date == 0) {
            date = now();
        }
        List<KeywordStats> keywordStatsList = keywordStatsService.getkeywordStats(date, limit);
        StringBuilder json = new StringBuilder("{\"status\": 0,\"data\": [");
        for (int i = 0; i < keywordStatsList.size(); i++) {
            KeywordStats keywordStats = keywordStatsList.get(i);
            json.append("{\"name\": \"")
                    .append(keywordStats.getKeyword())
                    .append("\",\"value\": ")
                    .append(keywordStats.getCt())
                    .append("}");
            if (i < keywordStatsList.size() - 1) {
                json.append(",");
            }
        }
        json.append("]}");

        return json.toString();
    }

    @RequestMapping("/hr")
    public String getVisitorStatsByHr(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }
        //从service中获取分时访问情况
        List<VisitorStats> visitorStatsList = visitorStatsService.getVisitorStatsByHr(date);
        //定义一个数组 ，用于存放24小时的分时统计情况
        VisitorStats[] visitorStatsArr = new VisitorStats[24];
        //从集合中获取结果，赋值给数组中对应的小时
        for (VisitorStats visitorStats : visitorStatsList) {
            visitorStatsArr[visitorStats.getHr()] = visitorStats;
        }

        //用于存放24小时的集合
        List<String> hrList = new ArrayList<>();
        //用于存放每个小时uv情况的集合
        List<Long> uvList = new ArrayList<>();
        //用于存放每个小时pv情况的集合
        List<Long> pvList = new ArrayList<>();
        //用于存放新访客每个小时uv情况的集合
        List<Long> newUvList = new ArrayList<>();

        //从数组中获取一天24的数据
        for (int hr = 0; hr < visitorStatsArr.length; hr++) {
            VisitorStats visitorStats = visitorStatsArr[hr];
            if (visitorStats != null) {
                uvList.add(visitorStats.getUv_ct());
                pvList.add(visitorStats.getPv_ct());
                newUvList.add(visitorStats.getNew_uv());
            } else {
                uvList.add(0L);
                pvList.add(0L);
                newUvList.add(0L);
            }
            hrList.add(String.format("%02d", hr));
        }

        return "{\"status\": 0,\"data\": {\"categories\": " +
                "[\"" + StringUtils.join(hrList, "\",\"") + "\"]," +
                "\"series\": [" +
                "  {\"name\": \"UV\",\"data\": [" + StringUtils.join(uvList, ",") + "]}," +
                "  {\"name\": \"PV\",\"data\": [" + StringUtils.join(pvList, ",") + "]}," +
                "  {\"name\": \"newUV\",\"data\": [" + StringUtils.join(newUvList, ",") + "]}" +
                "]}}";
    }


    @RequestMapping("/visitor")
    public String getVisitorStats(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }
        List<VisitorStats> visitorStatsList = visitorStatsService.getVisitorStats(date);
        VisitorStats newVisitorStats = new VisitorStats();
        VisitorStats oldVisitorStats = new VisitorStats();
        for (VisitorStats visitorStats : visitorStatsList) {
            if ("1".equals(visitorStats.getIs_new())) {
                //新访客
                newVisitorStats = visitorStats;
            } else {
                //老访客
                oldVisitorStats = visitorStats;
            }
        }

        return "{\"status\": 0,\"data\": " +
                "{\"columns\": [" +
                "{\"name\": \"类别\",\"id\": \"type\"}," +
                "{\"name\": \"新用户\",\"id\": \"new\"}," +
                "{\"name\": \"老用户\",\"id\": \"old\"}]," +
                "\"rows\": [" +
                "{\"type\": \"用户数(人)\",\"new\": " + newVisitorStats.getUv_ct() + ",\"old\": " + oldVisitorStats.getUv_ct() + "}," +
                "{\"type\": \"总访问页面(次)\",\"new\": " + newVisitorStats.getPv_ct() + ",\"old\": " + oldVisitorStats.getPv_ct() + "}," +
                "{\"type\": \"跳出率(%)\",\"new\": " + newVisitorStats.getUjRate() + ",\"old\": " + oldVisitorStats.getUjRate() + "}," +
                "{\"type\": \"平均在线时长(秒)\",\"new\": " + newVisitorStats.getDurPerSv() + ",\"old\": " + oldVisitorStats.getDurPerSv() + "}," +
                "{\"type\": \"平均访问页面数(次)\",\"new\": " + newVisitorStats.getPvPerSv() + ",\"old\": " + oldVisitorStats.getPvPerSv() + "}]}}";
    }

    @RequestMapping("/gmv")
    public String getGMV(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }

        //调用service获取总交易额
        BigDecimal gmv = productStatsService.getGmv(date);

        return "{\"status\": 0,\"data\": " + gmv + "}";
    }

    @RequestMapping("/tm")
    public String getProductStatsByTm(
            @RequestParam(value = "date", defaultValue = "0") Integer date,
            @RequestParam(value = "limit", defaultValue = "20") Integer limit) {
        if (date == 0) {
            date = now();
        }
        //调用service方法，获取品牌交易额
        List<ProductStats> productStatsList = productStatsService.getProductStatsByTm(date, limit);

        //对查询结果进行遍历，获取品牌以及品牌交易额；将品牌以及品牌交易额分别封装到独立的list集合中
        List<String> tmList = new ArrayList<>();
        List<BigDecimal> amountList = new ArrayList<>();
        for (ProductStats productStats : productStatsList) {
            tmList.add(productStats.getTm_name());
            amountList.add(productStats.getOrder_amount());
        }

        return "{\"status\": 0,\"data\": " +
                "{\"categories\": [\"" + StringUtils.join(tmList, "\",\"") + "\"]," +
                "\"series\": [{\"name\": \"商品品牌\",\"data\": [" + StringUtils.join(amountList, ",") + "]}]}}";
    }

    @RequestMapping("/category3")
    public Object getProductStatsByCategory3(
            @RequestParam(value = "date", defaultValue = "0") Integer date,
            @RequestParam(value = "limit", defaultValue = "20") Integer limit) {
        if (date == 0) {
            date = now();
        }

        //调用service方法，获取品类销售排名情况
        List<ProductStats> productStatsList = productStatsService.getProductStatsByCategory3(date, limit);

        Map<String, Object> resMap = new HashMap<>();
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (ProductStats productStats : productStatsList) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("name", productStats.getCategory3_name());
            dataMap.put("value", productStats.getOrder_amount());
            dataList.add(dataMap);
        }
        resMap.put("status", 0);
        resMap.put("data", dataList);
        return resMap;
    }

    @RequestMapping("/spu")
    public String getProductStatsBySPU(
            @RequestParam(value = "date", defaultValue = "0") Integer date,
            @RequestParam(value = "limit", defaultValue = "20") Integer limit) {
        if (date == 0) {
            date = now();
        }
        List<ProductStats> productStatsList = productStatsService.getProductStatsBySpu(date, limit);

        StringBuilder jsonB = new StringBuilder("{\"status\": 0,\"data\": {\"columns\": [{\"name\": \"商品名称\",\"id\": \"name\"},{\"name\": \"交易额\",\"id\": \"amount\"},{\"name\": \"订单数\",\"id\": \"ct\"}],\"rows\": [");

        for (int i = 0; i < productStatsList.size(); i++) {
            ProductStats productStats = productStatsList.get(i);
            jsonB.append("{\"name\": \"")
                    .append(productStats.getSpu_name())
                    .append("\",\"amount\": ")
                    .append(productStats.getOrder_amount())
                    .append(",\"ct\": ")
                    .append(productStats.getOrder_ct())
                    .append("}");
            if (i < productStatsList.size() - 1) {
                jsonB.append(",");
            }
        }

        jsonB.append("]}}");

        return jsonB.toString();
    }

    @RequestMapping("/province")
    public String getProvinceStats(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }
        List<ProvinceStats> provinceStatsList = provinceStatsService.getProvinceStats(date);

        StringBuilder json = new StringBuilder("{\"status\": 0,\"data\": {\"mapData\": [");

        for (int i = 0; i < provinceStatsList.size(); i++) {
            ProvinceStats provinceStats = provinceStatsList.get(i);
            if (i >= 1) {
                json.append(",");
            }
            json.append("{\"name\": \"")
                    .append(provinceStats.getProvince_name())
                    .append("\",\"value\": ")
                    .append(provinceStats.getOrder_amount())
                    .append("}");
        }
        json.append("], \"valueName\": \"交易额\"}}");

        return json.toString();
    }

    //获取当前日期
    private Integer now() {
        String yyyyMMdd = DateFormatUtils.format(new Date(), "yyyyMMdd");
        return Integer.valueOf(yyyyMMdd);
    }
}
